package com.sinooceangroup.capital.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sinooceangroup.capital.sentinel.feign.ProductorFeignClient;
import com.sinooceangroup.capital.sentinel.service.SentinelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * Sentinel Api Demo
 *
 * @author: Leo.Wang, adwyxx@qq.com
 * @date: 2020/8/5 10:16
 */
@RestController
public class SentinelController {

    @Autowired
    SentinelService sentinelService;
    @Autowired
    ProductorFeignClient productorFeignClient;

    @GetMapping("/sayHello/{name}")
    public String sayHello(@PathVariable("name") String name){
        return sentinelService.sayHello(name);
    }

    /***
     * 可以使用 blockHandler 属性指定限流处理逻辑，fallback 指定熔断处理逻辑
     * 注意：
     * 1.blockHandler函数访问范围需要是public，且blockHandler函数默认需要和原方法在同一个类中。
     * 2.参数类型需要和原方法相匹配并且最后加一个额外的参数，类型为BlockException。
     * 若希望使用其他类的函数，则可以指定 blockHandlerClass为对应的类的Class对象，注意对应的函数必须为 static 函数，否则无法解析。
     */
    @GetMapping("/block/{value}")
    //@SentinelResource(value = "block",blockHandler = "handleBlockException")
    public String block(@PathVariable("value") String value){
        return sentinelService.block(value);
    }
    /***
     * 限流操作处理，注意：最后要有一个BlockException类型参数
     */
    public String handleBlockException(String value, BlockException ex){
        ex.printStackTrace();
        return "handleBlock : 接口访问被限流了..."+value+"😭";
    }

    @GetMapping("/rt")
    public String block(){
        return sentinelService.rt();
    }

    @GetMapping("/exception-ratio")
    public String exceptionRatio() throws Exception {
        return sentinelService.exceptionRatio();
    }

    @GetMapping("/sentinel-feign")
    @SentinelResource(value = "sentinelFeign",fallback = "sentinelFeignFallBack")
    public String sentinelFeign(){
        return productorFeignClient.sentinelFeign();
    }

    public String sentinelFeignFallBack() {
        return "sentinelFeign 访问被熔断了,\r"+ UUID.randomUUID().toString();
    }
}
